<?php

namespace App\Http\Controllers\Api\v1\Goods;

use App\Handlers\KeysHandler;
use App\Http\Controllers\Api\v1\Controller;
use App\Http\Resources\GoodsCategoryResource;
use App\Models\GoodsCategory;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CategoryController extends Controller
{
    public function index(Request $request)
    {
/*
        $list = Cache::get(KeysHandler::GOODS_CATEGORY_DATA);
        if(!empty($list)){
            dump($list);
            return $this->success($list);
        }
        $lock = Cache::lock(KeysHandler::GOODS_CATEGORY_DATA_LOCK, 2);
        if(!$lock->get()) {
            usleep(100000); //睡眠100ms
            return $this->index();
        }
        $list =  GoodsCategory::getCategory(['id', 'title'], GoodsCategory::STATUS_YES, ['sort', 'asc']);
        // 'pic', 'sort'
        $list = GoodsCategoryResource::collection($list);
        if(!$list->isEmpty()) {
            $list = GoodsCategoryResource::collection($list);
            Cache::put(KeysHandler::GOODS_CATEGORY_DATA, $list, 300);
        }
        $lock->release();
        return $this->success($list);
*/

        $list = Cache::remember("GoodsCategory", 300, function () {
            $list = GoodsCategory::query()->select("id","title")->where('country','=',config('app.goods_country'))->where('status','=',GoodsCategory::STATUS_YES)->orderBy('sort', 'asc')->get()->toArray();
            $add[] = [
                'id' => -1,
                'title' => trans('error.10003')
            ];
            return array_merge($add,$list);
        });
        return $this->success($list);

    }

    public function shop(Request $request)
    {

        $list = Cache::get(KeysHandler::GOODS_CATEGORY_DATA);
        if(!empty($list)){
            return $this->success($list);
        }
        $lock = Cache::lock(KeysHandler::GOODS_CATEGORY_DATA_LOCK, 2);
        if(!$lock->get()) {
            usleep(100000); //睡眠100ms
            return $this->index();
        }
        $list =  GoodsCategory::getCategory(['id', 'title','pic'], GoodsCategory::STATUS_YES, ['sort', 'asc']);
        // 'pic', 'sort'
        $list = GoodsCategoryResource::collection($list);
        if(!$list->isEmpty()) {
            $list = GoodsCategoryResource::collection($list);
            Cache::put(KeysHandler::GOODS_CATEGORY_DATA, $list, 300);
        }
        $lock->release();
        return $this->success($list);


    }


}
